<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="increment">+1</button>
    <span id="count">0</span>
    <button id="decrement">-1</button>
    <button id="cancel">取消订阅</button>

    <script src="./mini-redux.js"></script>
    <script src="./logger.middleware.js"></script>
    <script src="./makeup.middleware.js"></script>
    <script>
        function countReducer(state=0, action) {
            switch(action.type) {
                case 'increment':
                    return state + (action.payload || 1)
                case 'decrement':
                    return state - (action.payload || 1)
                default:
                    return state
            }
        }

        function enhancer(createStore) {
            return function(reducer, preloadedState) {
                const store = createStore(reducer, preloadedState)
                const dispatch = store.dispatch
                function _dispatch (action) {
                    if(typeof action === 'function') {
                        return action(dispatch)
                    }
                    dispatch(action)
                }
                return {
                    ...store,
                    dispatch: _dispatch
                }
            }
        }

        // const store = createStore(countReducer, 0, enhancer)
        // console.log("store", store)

        const rootReducer = combineReducers({counter: countReducer})
        console.log("rootReducer", rootReducer)

        const store = createStore(rootReducer, {counter: 0}, applyMiddleware(logger, makeup))

        // const incrementAction = {type: 'increment'}
        // const decrementAction = {type: 'decrement'}
        const incrementAction = (payload) => ({type: 'increment', payload})
        const decrementAction = (payload) => ({type: 'decrement', payload})

        const actions = bindActionCreators({incrementAction, decrementAction}, store.dispatch)
        const action = bindActionCreators(incrementAction, store.dispatch)
        console.log("actions", actions)

        const unSubscribe = store.subscribe(() => {
            document.getElementById('count').innerHTML = store.getStore().counter
        })


        // document.getElementById('increment').onclick = () => store.dispatch(incrementAction)
        // document.getElementById('decrement').onclick = () => store.dispatch(decrementAction)
        document.getElementById('increment').onclick = () => actions.incrementAction(5)
        document.getElementById('decrement').onclick = () => actions.decrementAction(5)

        // document.getElementById('increment').onclick = () => action(100)

        document.getElementById('cancel').onclick = () => unSubscribe()
    </script>
</body>
</html>